package com.gy.algorithm.carl.tree;

import com.gy.datastructure.tree.Tree;
import net.sf.ehcache.pool.Pool;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @BelongsProject: javabase
 * @BelongsPackage: com.gy.algorithm.carl
 * @Author: gy
 * @Date: 2024/10/22 11:30
 * @Description:
 */
public class LevelOrder102 {

    public static void main(String[] args) {

    }

    // end
//    public static List<List<Integer>> levelOrder(TreeNode root) {
//
//    }

    // write
    public static List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> res = new ArrayList<>();
        if(null == root) return res;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            int size = queue.size();
            List<Integer> tmp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                tmp.add(poll.val);
                if(null != poll.left) queue.offer(poll.left);
                if(null != poll.right) queue.offer(poll.right);
            }
            res.add(tmp);
        }
        return res;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(null == root) return res;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if(null != poll.left) queue.offer(poll.left);
                if(null != poll.right) queue.offer(poll.right);
                if(i == size - 1) res.add(poll.val);
            }
        }

        return  res;
    }

}
